package com.mud.mudcommune.view.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.mud.mudcommune.R;
import com.mud.mudcommune.entry.CaseContentResponse;
import com.mud.mudcommune.entry.CaseEntry;
import com.mud.mudcommune.entry.SubjectEntry;
import com.mud.mudcommune.http.ApiService;
import com.mud.mudcommune.http.NetUtils;
import com.mud.mudcommune.utils.ImageSlideshow;
import com.mud.mudcommune.utils.LogUtils;
import com.mud.mudcommune.utils.MyLocationUtils;
import com.mud.mudcommune.view.fragment.threeLevel.WebViewFragment;
import com.mud.mudcommune.view.fragment.twoLevel.ArticleFragment;
import com.mud.mudcommune.view.fragment.twoLevel.CaseDetailsFragment;
import com.mud.mudcommune.view.fragment.twoLevel.ChiefFragment;
import com.mud.mudcommune.view.fragment.twoLevel.ContactFragment;
import com.mud.mudcommune.view.fragment.twoLevel.FreeFragment;
import com.mud.mudcommune.view.fragment.twoLevel.HotRecommendFragment;
import com.mud.mudcommune.view.fragment.twoLevel.SubjectFragment;
import com.mud.mudcommune.view.fragment.twoLevel.VrFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomePagerFragment extends Fragment implements AMapLocationListener, Callback<CaseContentResponse> {
    private static final String TAG = "HomePagerFragment";
    @BindView(R.id.is_gallery)
    ImageSlideshow imageSlideshow;
    @BindView(R.id.designer_img)
    TextView designer;
    @BindView(R.id.leader_img)
    TextView leader;
    @BindView(R.id.decorate_img)
    TextView decorate;
    @BindView(R.id.map)
    TextView location;
    @BindView(R.id.message)
    ImageView message;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.text_title)
    TextView title;
    @BindView(R.id.text_details)
    TextView details;
    @BindView(R.id.image02)
    ImageView image02;
    @BindView(R.id.text_title02)
    TextView title02;
    @BindView(R.id.text_details02)
    TextView details02;
    @BindView(R.id.time02)
    TextView time02;
    @BindView(R.id.image03)
    ImageView image03;
    @BindView(R.id.text_title03)
    TextView title03;
    @BindView(R.id.text_details03)
    TextView details03;
    @BindView(R.id.time03)
    TextView time03;
    @BindView(R.id.hop_more)
    TextView hopMore;
    @BindView(R.id.vr_layout)
    RelativeLayout vrLayout;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.more)
    TextView more;
    @BindView(R.id.article)
    RelativeLayout article;
    @BindView(R.id.free_Apply)
    RelativeLayout free_Apply;
    @BindView(R.id.topic_img_one)
    ImageView topic_one;
    @BindView(R.id.topic_img_two)
    ImageView topic_two;
    private static TextView cityName;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private List<String> imageUrlList;
    private List<String> titleList;

    private static final HomePagerFragment fragment = new HomePagerFragment();
    private static CaseFragment caseFragment = new CaseFragment();
    private List<CaseEntry> caseContentList;
    private List<SubjectEntry.Subject> data = null;
    private SubjectEntry.Subject subject1;
    private SubjectEntry.Subject subject2;
    private boolean isClick = true;

    public static Fragment getInstance() {
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        imageSlideshow = (ImageSlideshow) view.findViewById(R.id.is_gallery);
        imageUrlList = new ArrayList<>();
        titleList = new ArrayList<>();
        requestDate();
        RequesTopicData();//请求轮播图
        initData();//轮播图预加载
        initLocation();
        // 为ImageSlideshow设置数据
        imageSlideshow.setDotSpace(12);
        imageSlideshow.setDotSize(12);
        imageSlideshow.setDelay(3000);
        imageSlideshow.commit();
        cityName = (TextView) view.findViewById(R.id.map);
    }

    // 请求数据
    private void requestDate() {
        NetUtils.createService(ApiService.class,ApiService.BASE_URL).getRecommend().enqueue(this);
    }

    private void initData() {
        String[] imageUrls = {"http://img.n8guanjia.com/2016/10/17/162301/e3958ad9-7449-4400-830f-009893c138fd.jpg",
                "http://img.n8guanjia.com/2016/10/17/162233/69c39bae-197e-41d5-b79b-db42b8fe537f.jpg"};

        for (int i = 0; i < 2; i++) {
            imageSlideshow.addImageTitle(imageUrls[i], null);
        }
    }

    public static void getcity(String cityname) {
        if (cityname != null) {
            cityName.setText(cityname);
        }
    }

    @Override
    public void onDestroy() {
        imageSlideshow.releaseResource();
        super.onDestroy();
        mLocationClient.unRegisterLocationListener(this);
        mLocationClient = null;
    }

    @OnClick({R.id.decorate_img, R.id.designer_img, R.id.leader_img, R.id.message, R.id.map,
            R.id.hop_more, R.id.vr_layout, R.id.article, R.id.free_Apply, R.id.more,
            R.id.image, R.id.image02, R.id.image03, R.id.topic_img_one, R.id.topic_img_two})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.image:
                caseDetailsFragment(0);
                break;
            case R.id.image02:
                caseDetailsFragment(1);
                break;
            case R.id.image03:
                caseDetailsFragment(2);
                break;
            case R.id.decorate_image:
                break;
            case R.id.designer_img:
                getFragmentManager().beginTransaction()
                        .hide(MainFragment.getInstance())//上拉刷新下面还有层布局
                        .add(R.id.main_frame, ChiefFragment.getInstance())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.leader_img:
                break;
            case R.id.map:
                getFragmentManager().beginTransaction()
                        .hide(HomePagerFragment.getInstance())
                        .add(R.id.main_frame, ContactFragment.getInstance())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.message:
                break;
            case R.id.hop_more:
                getFragmentManager()
                        .beginTransaction()
                        .hide(HomePagerFragment.getInstance())
                        .add(R.id.main_frame, HotRecommendFragment.getInstance())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.vr_layout:
                getFragmentManager()
                        .beginTransaction()
                        .hide(HomePagerFragment.getInstance())
                        .add(R.id.main_frame, VrFragment.getInstance())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.article:
                getFragmentManager()
                        .beginTransaction()
                        .hide(HomePagerFragment.getInstance())
                        .add(R.id.main_frame, ArticleFragment.getInstance())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.decorate_img:
                CaseFragment();
                break;
            case R.id.free_Apply:
                getFragmentManager().beginTransaction()
                        .hide(MainFragment.getInstance())
                        .add(R.id.main_frame, FreeFragment.getInstance())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.more:
                getFragmentManager().beginTransaction()
                        .hide(fragment)
                        .add(R.id.main_frame, SubjectFragment.getInstance())//活动专题界面
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.topic_img_one:
                if (data != null) {
                    subject1 = data.get(0);
                    Fragment webview_one = WebViewFragment.getInstance();
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("Subject", subject1.getTopic_url());
                    webview_one.setArguments(bundle1);
                    getFragmentManager().beginTransaction()
                            .hide(fragment)
                            .add(R.id.main_frame, WebViewFragment.getInstance())
                            .addToBackStack(null)
                            .commit();
                }
                break;
            case R.id.topic_img_two:
                if (data != null) {
                    subject2 = data.get(1);
                    Fragment webview_two = WebViewFragment.getInstance();
                    Bundle bundle2 = new Bundle();
                    bundle2.putString("Subject", subject2.getTopic_url());
                    webview_two.setArguments(bundle2);
                    getFragmentManager().beginTransaction()
                            .hide(fragment)
                            .add(R.id.main_frame, WebViewFragment.getInstance())
                            .addToBackStack(null)
                            .commit();
                }
                break;
        }
    }

    private void RequesTopicData() {
        NetUtils.createService(ApiService.class, ApiService.BASE_URL).getSubject()
                .enqueue(new Callback<SubjectEntry>() {
                    @Override
                    public void onResponse(Call<SubjectEntry> call, Response<SubjectEntry> response) {
                        SubjectEntry body = response.body();
                        data = body.getData();
                        if (data != null) {//专题页面两站图
                            Glide.with(getActivity()).load(data.get(0).getTopic_img()).placeholder(R.drawable.pic_two).override(325, 170).centerCrop().into(topic_one);
                            Glide.with(getActivity()).load(data.get(1).getTopic_img()).placeholder(R.drawable.pic_one).override(325, 170).centerCrop().into(topic_two);
                        }
                    }

                    @Override
                    public void onFailure(Call<SubjectEntry> call, Throwable t) {
                        LogUtils.e(TAG, "类名>>HomePagerFragment>>方法名>>onFailure()" + t.getMessage());
                    }
                });
    }

    private void caseDetailsFragment(int index) {
        if (isClick) {
            isClick = false;
            Fragment mCaseDetailsFragment = CaseDetailsFragment.getInstance();
            Bundle bundle = new Bundle();
            bundle.putInt("type", ApiService.TYPE_CASE);
            if (caseContentList != null) {
                bundle.putInt("caseId", caseContentList.get(index).getCaseId());
                mCaseDetailsFragment.setArguments(bundle);
            }
            getFragmentManager().beginTransaction()
                    .hide(HomePagerFragment.getInstance())
                    .add(R.id.main_frame, mCaseDetailsFragment)
                    .addToBackStack(null)
                    .commit();
            isClick = true;
        }
    }

    public void CaseFragment() {
        if (caseFragment.isAdded()) {
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.remove(caseFragment);
            ft.hide(fragment)
                    .add(R.id.main_frame, caseFragment)
                    .addToBackStack(null)
                    .commit();
        } else {
            getFragmentManager().beginTransaction()
                    .hide(fragment)
                    .add(R.id.main_frame, caseFragment)
                    .addToBackStack(null)
                    .commit();
        }
    }

    private Handler mHandler = new Handler() {
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                //开始定位
                case MyLocationUtils.MSG_LOCATION_START:
                    break;
                // 定位完成
                case MyLocationUtils.MSG_LOCATION_FINISH:
                    AMapLocation loc = (AMapLocation) msg.obj;
                    String result = MyLocationUtils.getReportLocationStr(loc);
                    if ("定位失败".equals(result)) {
                        location.setText("长沙市");
                        LogUtils.e(TAG, "类名>>HomePagerFragment>>方法名>>dispatchMessage()>>>定位失败");

                    } else {
                        location.setText(result);
                    }
                    break;
                //停止定位
                case MyLocationUtils.MSG_LOCATION_STOP:
                    LogUtils.e(TAG, "类名>>HomePagerFragment>>方法名>>dispatchMessage()>>>定位停止");
                    break;
                default:
                    break;
            }
        }
    };

    public void initLocation() {
        mLocationClient = new AMapLocationClient(getContext());
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //获取一次定位结果
        mLocationOption.setOnceLocation(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        //mHandler.sendEmptyMessage(MyLocationUtils.MSG_LOCATION_START);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            Message message = mHandler.obtainMessage();
            message.obj = aMapLocation;
            message.what = MyLocationUtils.MSG_LOCATION_FINISH;
            mHandler.sendMessage(message);
        }
    }

    @Override
    public void onResponse(Call<CaseContentResponse> call, Response<CaseContentResponse> response) {
        caseContentList = response.body().getCaseContentList();
        if (caseContentList != null && caseContentList.size() > 0) {
            CaseEntry caseEntry = caseContentList.get(0);
            Glide.with(getContext())
                    .load(caseEntry.getCase_img()).placeholder(R.drawable.hot_one)
                    .into(image);
            title.setText(caseEntry.getCaseName());
            details.setText(caseEntry.getCaseDesc());
            if (caseEntry.getAddTime() != null) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date(Long.valueOf(caseEntry.getAddTime()));
                // 将时间戳换成日期格式显示
                time.setText(simpleDateFormat.format(date));
            }
            CaseEntry caseEntry02 = caseContentList.get(1);
            if (caseEntry02 != null) {
                Glide.with(getContext())
                        .load(caseEntry02.getCase_img()).placeholder(R.drawable.hot_two)
                        .into(image02);
                title02.setText(caseEntry02.getCaseName());
                details02.setText(caseEntry02.getCaseDesc());
                if (caseEntry02.getAddTime() != null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = new Date(Long.valueOf(caseEntry02.getAddTime()));
                    // 将时间戳换成日期格式显示
                    time02.setText(simpleDateFormat.format(date));
                }
            }

            CaseEntry caseEntry03 = caseContentList.get(2);
            if (caseEntry03 != null) {
                Glide.with(getContext())
                        .load(caseEntry03.getCase_img()).placeholder(R.drawable.hot_three)
                        .into(image03);
                title03.setText(caseEntry03.getCaseName());
                details03.setText(caseEntry03.getCaseDesc());
                if (caseEntry03.getAddTime() != null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = new Date(Long.valueOf(caseEntry03.getAddTime()));
                    // 将时间戳换成日期格式显示
                    time03.setText(simpleDateFormat.format(date));
                }
            }
        }
    }

    @Override
    public void onFailure(Call<CaseContentResponse> call, Throwable t) {
        t.printStackTrace();
    }
}